package com.zsck.zsgy.http

import com.blankj.utilcode.util.LogUtils
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.zsck.commonbase.BaseApp
import com.zsck.commonbase.BuildConfig
import com.zsck.commonbase.http.cookie.CookieJarImpl
import com.zsck.commonbase.http.cookie.MemoryCookieStore
import com.zsck.commonbase.http.factory.GsonDConverterFactory
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.io.File
import java.util.concurrent.TimeUnit


class RetrofitFactory {

    companion object {
        val INSTANCE: RetrofitFactory by lazy { RetrofitFactory() }
    }

    private val interceptor: Interceptor
    init {
        interceptor = Interceptor { chain -> val request = chain.request()
            .newBuilder()
            .addHeader("Authorization", "")
            .addHeader("memberId", "")
            .addHeader("userName", "")
            .addHeader("sourceType", "h5")
            .build()
            chain.proceed(request)
        }
    }

    fun factory(): Retrofit {
        // 获取retrofit的实例
        return Retrofit.Builder()
            .baseUrl(BuildConfig.API_HOST)
            .client(getOkHttpClient())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonDConverterFactory.create())
            .build()

    }


    private fun getOkHttpClient(): OkHttpClient? {
        //设置 请求的缓存的大小跟位置
        val cacheFile = File(BaseApp.getContext().cacheDir, "cache")
        val cache = Cache(cacheFile, 1024 * 1024 * 100) //100Mb 缓存的大小
        val logInterceptor = HttpLoggingInterceptor(HttpLogger()) //创建拦截对象


        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY) //这一句一定要记得写，否则没有数据输出

        var client: OkHttpClient = OkHttpClient.Builder()
            .connectTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(10L, TimeUnit.SECONDS)
            .writeTimeout(10L, TimeUnit.SECONDS)
            .addNetworkInterceptor(StethoInterceptor())
            .addInterceptor(interceptor) // header
            .addInterceptor(logInterceptor)
            .cache(cache)  //添加缓存
            .cookieJar(CookieJarImpl(MemoryCookieStore()))
            .build()
        return client


    }

    private fun initLogInterceptor(): HttpLoggingInterceptor {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return interceptor
    }


    inner class HttpLogger :HttpLoggingInterceptor.Logger{

        override fun log(message: String) {
            if(BuildConfig.DEBUG){
                LogUtils.d("OkHttpLogInfo :" + message)
            }

        }

    }
}